package com.orangelife.mobile.login.activity;

/**
 * 重设密码
 * 虽然这个的类名是重置密码，但是！因为需求改了，修改密码直接这样做，类似重置密码，就跳到这边
 *
 * @author yw
 */

import android.content.Context;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.common.sp.UserSp;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.login.biz.LoginBiz;
import com.orangelife.mobile.pay.biz.PayPwdHttpBiz;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.util.CryptoDES;
import com.orangelife.mobile.verify.biz.VerifyCodeBiz;

import org.json.JSONObject;

import java.util.HashMap;

public class ResetPwdActivity extends OrangeLifeBaseActivity {
    /* 电话号码、密码、验证码 */
    private EditText etPwd, etValidateCode;
    /* 提交按钮 */
    private Button btnSubmit;
    private TextView tvPhone, tvGetCode, tvVoiceCode;
    private boolean isPayPwd;
    VerifyCodeBiz verifyCodeBiz;

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_change_pwd_v3);
        getIntentInfo();
        initView();
        setListener();
    }

    private void getIntentInfo() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isPayPwd = bundle.getBoolean("isPayPwd");
        }
    }

    public void hideInput(View v) {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    private void initView() {
        TextView tvResetTitle;
        TextView tvTextSetPwd;
        tvResetTitle = (TextView) findViewById(R.id.tv_title);
        tvPhone = (TextView) findViewById(R.id.tvPhoneNum);
        etPwd = (EditText) findViewById(R.id.et_reset_pwd);
        etValidateCode = (EditText) findViewById(R.id.et_code);
        tvGetCode = (TextView) findViewById(R.id.btn_get_code);
        tvTextSetPwd = (TextView) findViewById(R.id.tvTextSetPwd);
        tvVoiceCode = (TextView) findViewById(R.id.tvVoiceCode);
        btnSubmit = (Button) findViewById(R.id.btn_submit);
        if (isPayPwd) {
            tvResetTitle.setText("修改支付密码");
            tvTextSetPwd.setText("支付密码");
            etPwd.setHint("6位纯数字");
            etPwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
        } else {
            tvResetTitle.setText("修改密码");
            etPwd.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
//            tvTextSetPwd.setText("设置密码");
        }
        verifyCodeBiz = new VerifyCodeBiz(this, tvGetCode, tvVoiceCode, etValidateCode);
    }

    private void setListener() {
        String phone = UserSp.getRegPhone();
        tvPhone.setText(phone);
        tvGetCode.setOnClickListener(clickListener);
        btnSubmit.setOnClickListener(clickListener);
        tvVoiceCode.setOnClickListener(clickListener);
    }

    /**
     * 监听器——根据id判断并执行相应操作
     */
    View.OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            String phone = UserSp.getRegPhone();
            switch (v.getId()) {
                case R.id.btn_get_code:
                    if (verifyCodeBiz != null) {
                        verifyCodeBiz.onClickGetCode(true);
                    }
                    break;
                case R.id.tvVoiceCode:
                    if (verifyCodeBiz != null) {
                        verifyCodeBiz.onClickGetCode(false);
                    }
                    break;
                case R.id.btn_submit:
                    String password = etPwd.getText().toString();
                    String code = etValidateCode.getText().toString();
                    if (validate()) {
                        requestCommitPwd(phone, password, code);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void requestCommitPwd(String phone1, String password,
                                  String code) {

        if (password != null && password.length() != 6) {
            String msg = "支付密码需要6位";
            if (!isPayPwd) {
                msg = "密码需要6位";
            }
            ToastHelper.getInstance()._toast(msg);
            return;
        }
        showDialog();
        if (isPayPwd) {
            requestModPayPwd(password, code);
        } else {
            requestModLoginPwd(phone1, password, code);
        }
    }

    /** 修改支付密码 */
    private void requestModPayPwd(String password,
                                  String code) {
        PayPwdHttpBiz.modPayPwd(password, code, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                closeDialog();
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    ToastHelper.getInstance()._toast("支付密码修改成功");
                    finish();
                }
            }
        });
    }

    /**
     * 提交修改
     *
     * @param phone    手机
     * @param password 密码
     * @param code     验证码
     */
    private void requestModLoginPwd(String phone, String password,
                                    String code) {
        try {
            phone = CryptoDES.encrypt(phone, Constant.DES_KEY);
            password = StringUtil.md5(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("memberName", phone);
        map.put("verifyCode", code);
        map.put("memberPsw", password);
        VolleyHttpUtil.getInstance().putWithCallback(Constant.PATH_RESET_PWD, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                closeDialog();
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    ToastHelper.getInstance()._toast("修改密码成功");
                    finish();
                }
            }
        });
    }

    private boolean validate() {
        String password = etPwd.getText().toString();
        String code = etValidateCode.getText().toString();
        if (StringUtil.isContainBlank(code)) {
            ToastHelper.getInstance().displayToastWithQuickClose(
                    getResources().getString(
                            R.string.verification_code_null));
            return false;
        } else if (StringUtil.isContainBlank(password)) {
            ToastHelper.getInstance().displayToastWithQuickClose(
                    getResources().getString(R.string.password_null));
            return false;
        }
        return LoginBiz.validatePhoneNum(UserSp.getRegPhone(), this);
    }

}